//
// P2P.js
//
// Connecting the Messenger P2P network stack to the silverlight control
//
// Make sure the SilverlightPlugin OnLoad event is handled by the 
// silverlightControl_OnLoad function for proper initialization.
//

var silverlightControl;
var timeoutId;
var initialized = false;
var eventQueue = new Array();
var loadState = 0;

function wnd_onload(){
    loadState++;
    startApp();
}

function silverlightControl_OnLoad(sender, args){
    silverlightControl = sender;
    
    // attach event handlers
    silverlightControl.Content.P2PInterop.ChannelCloseApp = P2PInterop_ChannelCloseApp;
    silverlightControl.Content.P2PInterop.ChannelEnterIM = P2PInterop_ChannelEnterIM;
    silverlightControl.Content.P2PInterop.ChannelSendData = P2PInterop_ChannelSendData;
    silverlightControl.Content.P2PInterop.ChannelSendIM = P2PInterop_ChannelSendIM;
    silverlightControl.Content.P2PInterop.ChannelSendIMAsUser = P2PInterop_ChannelSendIMAsUser;
    silverlightControl.Content.P2PInterop.WindowOpen = P2PInterop_WindowOpen;
    
    loadState++;
    startApp();
}

function startApp(){
    if (loadState == 2){
        // initializes the control & p2p 
        var hostedInMessenger = window.external != null && window.external.Channel != null;

        // register users
        if (hostedInMessenger){
            var users = window.external.Users;
            for(var i = 0; i < users.Count; i++){
                var user = users.Item(i);

                var email = user.Email ? user.Email : "";
                var globalIp = user.GlobalIP ? user.GlobalIP : "";
                var localIp = user.LocalIP ? user.LocalIP : "";
                var name = user.Name ? user.Name : "";
                var puid = user.PUID ? user.PUID : "";
                var isMe = (users.Me == user);
                var isInviter = (users.Inviter == user);
                
                silverlightControl.Content.P2PInterop.AddUser(email, globalIp, localIp, name, puid, isMe, isInviter);
            }
        }

        silverlightControl.Content.P2PInterop.SetState(hostedInMessenger ? 1 : 5);
        
        if (hostedInMessenger){
            window.external.Channel.Initialize();
            // dequeue pending events
            for (var i = 0; i < eventQueue.length; i++){
                eval("silverlightControl.Content.P2PInterop." + eventQueue[i]);
            }

            initialized = true;
        }
    }
}

// P2P interop events
function P2PInterop_ChannelCloseApp(sender, args){
    try{
        window.external.CloseApp();
    }
    catch(e){
        raiseException(e);
    }
}

function P2PInterop_ChannelEnterIM(sender, args){
    try{
        window.external.Channel.EnterIM(args.Data);
    }
    catch(e){
        raiseException(e);
    }
}

function P2PInterop_ChannelSendData(sender, args){
    try{
        window.external.Channel.SendData(args.Data);
    }
    catch(e){
        raiseException(e);
    }
}

function P2PInterop_ChannelSendIM(sender, args){
    try{
        window.external.Channel.SendIM(args.Data);
    }
    catch(e){
        raiseException(e);
    }
}

function P2PInterop_ChannelSendIMAsUser(sender, args){
    try{
        window.external.Channel.SendIMAsUser(args.Data);
    }
    catch(e){
        raiseException(e);
    }
}

function P2PInterop_WindowOpen(sender, args){
    window.open(args.Data);
}

// P2P channel events
function Channel_OnAppClose(){
    if (initialized){
        silverlightControl.Content.P2PInterop.Channel_OnAppClose();
    }
    else{
        eventQueue.push("Channel_OnAppClose()");
    }
}

function Channel_OnDataError(){
    var error = window.external.Channel.Error;
    var type = error.Type;
    var data = error.Data.toString();
    
    if (initialized){
        silverlightControl.Content.P2PInterop.Channel_OnDataError(type, data);
    }
    else{
        eventQueue.push("Channel_OnDataError(" + type + ", \"" + escapeQuote(data) + "\")");
    }
}

function Channel_OnDataReceived(){
    var data = window.external.Channel.Data.toString();
    if (initialized){
        silverlightControl.Content.P2PInterop.Channel_OnDataReceived(data);
    }
    else{
        eventQueue.push("Channel_OnDataReceived(\"" + escapeQuote(data) + "\")");
    }
}

function Channel_OnIMReceived(){
    var im = window.external.Channel.IM;
    if (initialized){
        window.external.Channel.IM = silverlightControl.Content.P2PInterop.Channel_OnIMReceived(im);
    }
    else{
        // note: setting IM in queued scenario not supported
        eventQueue.push("Channel_OnIMReceived(\"" + escapeQuote(im) + "\")");
    }
}

function Channel_OnRemoteAppClosed(){
    if (initialized){
	    silverlightControl.Content.P2PInterop.Channel_OnRemoteAppClosed();
	}
	else{
	    eventQueue.push("Channel_OnRemoteAppClosed()");
	}
}

function Channel_OnRemoteAppLoaded(){
    if (initialized){
        silverlightControl.Content.P2PInterop.Channel_OnRemoteAppLoaded();
    }
    else{
        eventQueue.push("Channel_OnRemoteAppLoaded()");
    }
}

function Channel_OnTypeChanged(){
    var type = window.external.Channel.Type;
    if (initialized){
	    silverlightControl.Content.P2PInterop.Channel_OnTypeChanged(type);
	}
	else{
	    eventQueue.push("Channel_OnTypeChanged(" + type + ")");
	}
}

function raiseException(e){
    silverlightControl.Content.P2PInterop.RaiseP2PException(e.number, e.description);
}

function escapeQuote(data){
    return data.toString().replace("\"", "\\\"")
}

window.attachEvent("onload", wnd_onload);